package tt.dz.order.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import tt.dz.order.dao.SysApplicationContextAware;
import tt.dz.order.exception.BusinessException;
import tt.dz.order.pojo.*;
import tt.dz.order.service.drools.ActivityRuleService;
import tt.dz.order.service.rpc.client.MsRpcClient;
import tt.dz.order.util.AmountUtil;
import tt.dz.order.util.OrderConstant;
import tt.dz.order.util.OrderConstant.CRUDCode;
import tt.dz.order.util.OrderConstant.OrderStatus;
import tt.dz.order.util.UUIDUtil;
import tt.dz.order.util.page.Pagination;
import tt.dz.order.vo.*;
import tt.dz.webframe.authen.entity.RoleAndPermConstants;
import tt.dz.webframe.authen.service.AuthService;

import javax.annotation.Resource;

/**
 * @Title 订单系统运营管理服务类
 * @author zhoutian
 * @date 2015-11-17
 */
@Service("operationManagementService")
public class OperationManagementService {
	private static Logger log = LoggerFactory.getLogger(OperationManagementService.class);

	@Autowired
	private ActivityRuleService activityRuleService;
	// 商户的私钥
	@Value(value = "${allipay.publickey}")
	private String publickey;
	@Value(value = "${allipay.privatekey}")
	private String privatekey;
	@Value(value = "${allipay.appid}")
	private String appid;
	@Resource(name="tt.dz.webframe.authen.service.authService")
	  private AuthService authService;
	public OperationManagementService() {
	}

	/**
	 * 服务列表查询
	 */
	public List<OrderServiceInfo> listOrderServiceInfo() {
		log.info("服务列表查询service层");
		List<OrderServiceInfo> serviceInfoList = OrderServiceInfo.getAll();
		return serviceInfoList;
	}

	/**
	 * 查询所有的一级服务
	 */
	public List<OrderServiceInfo> listLevel1OrderServiceInfo() {
		log.info("服务列表查询service层");
		List<OrderServiceInfo> serviceInfoList = OrderServiceInfo.getAllLevelOne();
		return serviceInfoList;
	}

	/**
	 * 查询所有的二级服务
	 */
	public List<OrderServiceInfo> listLevel2OrderServiceInfo() {
		log.info("服务列表查询service层");
		List<OrderServiceInfo> serviceInfoList = OrderServiceInfo.getAllLevelTwo();
		return serviceInfoList;
	}

	/**
	 * 服务基本信息新增 /修改
	 */
	public void saveOrUpdateOrderServiceInfo(OrderServiceInfo orderServiceInfo) throws BusinessException {
		log.info("服务基本信息新增 /修改service层");
		String serviceNo = orderServiceInfo.getServiceNo();
		if (serviceNo == null || serviceNo.trim().length() == 0) {
			String parentServiceNo = orderServiceInfo.getParentNo();
			String maxServiceNo = OrderServiceInfo.getMaxServiceNoBy(parentServiceNo);
			orderServiceInfo.setServiceNo(String.valueOf(Integer.valueOf(maxServiceNo) + 1));
			if (orderServiceInfo.getServiceNo().equals(orderServiceInfo.getVirtualNo())) {
				throw new BusinessException("不允许把服务对应的虚拟服务设置为自身");
			}
			orderServiceInfo.setCreateTime(new Date());
			orderServiceInfo.save();
		} else {
			if (orderServiceInfo.getServiceNo().equals(orderServiceInfo.getVirtualNo())) {
				throw new BusinessException("不允许把服务对应的虚拟服务设置为自身");
			}
			if (orderServiceInfo.getIsVirtual() == 0) {
				if (OrderServiceInfo.isRelatedVirtual(orderServiceInfo.getServiceNo())) {
					throw new BusinessException("有其他服务关联了此服务，不能将此服务设置为非虚拟服务");
				}
			} else {
				if (OrderServiceInfo.hasOtherVirtualService(orderServiceInfo.getServiceNo())) {
					throw new BusinessException("此服务关联了其他虚拟服务，不能将此服务设置为虚拟服务");
				}
			}
			orderServiceInfo.update();
		}
	}

	/**
	 * 根据服务号删除服务
	 */
	public void deleteOrderServiceInfo(String serviceNo) {
		log.info("根据服务号删除服务service层");
		OrderServiceInfo orderServiceInfo = OrderServiceInfo.getById(serviceNo);
		orderServiceInfo.delete();
	}

	/**
	 * 运营商提供服务的查询
	 */
	public List<ProviderService> listProviderService() {
		log.info("服务列表查询service层");
		List<ProviderService> providerServiceList = ProviderService.getAll();
		return providerServiceList;
	}

	/**
	 * 运营商提供服务的新增 /修改
	 * 
	 * @throws BusinessException
	 */
	public void saveOrUpdateProviderService(ProviderService providerService, String saveOrUpdate)
			throws BusinessException {
		log.info("运营商提供服务的新增 /修改service层");
		if (saveOrUpdate.equalsIgnoreCase(CRUDCode.Create.value())) {
			providerService.setCreateTime(new Date());
			providerService.save();
		} else {
			providerService.update();
		}
	}

	/**
	 * 根据服务编号和运营商编号删除服务
	 */
	public void deleteProviderService(String serviceNo, String serviceProviderCode) {
		log.info("根据服务编号和运营商编号删除服务service层");
		ProviderService ps = ProviderService.getProviderServiceBy(serviceNo, serviceProviderCode);
		ps.delete();
	}

	/**
	 * 活动规则的查询
	 */
	public List<ActivityRule> listActivityRule() {
		log.info("活动规则的查询service层");
		List<ActivityRule> activityRuleList = ActivityRule.getAllRulesForOperationManagement();
		return activityRuleList;
	}

	/**
	 * 活动规则的新增 /修改
	 * 
	 * @throws BusinessException
	 */
	public void saveOrUpdateActivityRule(ActivityRule activityRule, String saveOrUpdate) throws BusinessException {
		log.info("活动规则的新增 /修改service层");
		if (saveOrUpdate.equalsIgnoreCase(CRUDCode.Create.value())) {
			activityRule.setCreateTime(new Date());
			activityRule.save();
		} else {
			activityRule.update();
		}
		activityRuleService.reBuildContainer();
	}

	/**
	 * 根据服务编号和运营商编号删除活动规则
	 */
	public void deleteActivityRule(String serviceNo, String serviceProviderCode) {
		log.info("根据服务编号和运营商编号删除服务service层");
		ActivityRule ar = ActivityRule.getBy(serviceNo, serviceProviderCode);
		ar.delete();
		activityRuleService.reBuildContainer();
	}

	/**
	 * 单价计量单位查询
	 */
	public List<OrderUnit> listOrderUnit() {
		log.info("单价计量单位查询service层");
		List<OrderUnit> orderUnitList = OrderUnit.getAll();
		return orderUnitList;
	}

	/**
	 * 单价计量单位新增 /修改
	 * 
	 * @throws BusinessException
	 */
	public void saveOrUpdateOrderUnit(OrderUnit orderUnit) throws BusinessException {
		log.info("单价计量单位新增 /修改service层");
		Integer unitNo = orderUnit.getUnitNo();
		if (unitNo == null) {
			Integer maxUnitNo = OrderUnit.getMaxUnitNo();
			orderUnit.setUnitNo(maxUnitNo + 1);
			orderUnit.setCreateTime(new Date());
			orderUnit.save();
		} else {
			orderUnit.update();
		}
	}

	/**
	 * 根据计量单位编号删除计量单位
	 */
	public void deleteOrderUnit(Integer unitNo) {
		log.info("根据计量单位编号删除计量单位service层");
		OrderUnit ou = OrderUnit.getBy(unitNo);
		ou.delete();
	}

	/**
	 * 资源信息查询
	 */
	public List<SysResource> listSysResource() {
		log.info("资源信息查询service层");
		List<SysResource> sysResourceList = SysResource.getAll();
		return sysResourceList;
	}

	/**
	 * 资源信息查询
	 */
	public List<SysResource> listValidSysResource() {
		log.info("资源信息查询service层");
		List<SysResource> sysResourceList = SysResource.getAllValid();
		return sysResourceList;
	}

	/**
	 * 资源信息新增 /修改
	 * 
	 * @throws BusinessException
	 */
	public void saveOrUpdateSysResource(SysResource sysResource) throws BusinessException {
		log.info("资源信息新增 /修改service层");
		String resourceId = sysResource.getResourceId();
		if (StringUtils.isBlank(resourceId)) {
			Integer maxNo = SysResource.getMaxSeqNo();
			sysResource.setResourceId(String.valueOf(Integer.valueOf(maxNo) + 1));
			sysResource.setSort(maxNo + 1);
			sysResource.setCreateTime(new Date());
			sysResource.save();
		} else {
			sysResource.update();
		}
	}

	/**
	 * 资源删除
	 */
	public void deleteSysResource(String resourceId) {
		log.info("资源删除service层");
		SysResource sysResource = SysResource.getBy(resourceId);
		sysResource.delete();
	}

	/**
	 * 菜单信息查询
	 */
	public List<SysMenu> listSysMenu() {
		log.info("菜单信息查询service层");
		List<SysMenu> sysMenuList = SysMenu.getAll();
		return sysMenuList;
	}

	/**
	 * 有效菜单信息查询
	 */
	public List<SysMenu> listValidSysMenu() {
		log.info("菜单信息查询service层");
		List<SysMenu> sysMenuList = SysMenu.getAllValid();
		return sysMenuList;
	}

	/**
	 * 菜单信息新增 /修改
	 * 
	 * @throws BusinessException
	 */
	public void saveOrUpdateSysMenu(SysMenu sysMenu) throws BusinessException {
		log.info("菜单信息新增 /修改service层");
		String menuId = sysMenu.getMenuId();
		if (StringUtils.isBlank(menuId)) {
			Integer maxNo = SysMenu.getMaxSeqNo();
			sysMenu.setMenuId(String.valueOf(Integer.valueOf(maxNo) + 1));
			sysMenu.setSort(maxNo + 1);
			sysMenu.setCreateTime(new Date());
			sysMenu.save();
		} else {
			sysMenu.update();
		}
	}

	/**
	 * 菜单删除
	 */
	public void deleteSysMenu(String menuId) {
		log.info("菜单删除service层");
		SysMenu sysMenu = SysMenu.getBy(menuId);
		sysMenu.delete();
	}

	/**
	 * 角色与资源对应关系查询
	 */
	public List<SysRoleRes> listSysRoleRes() {
		log.info("角色与资源对应关系查询service层");
		List<SysRoleRes> sysRoleResList = SysRoleRes.getAll();
		return sysRoleResList;
	}

	/**
	 * 角色与资源对应关系新增 /修改
	 * 
	 * @throws BusinessException
	 */
	public void saveOrUpdateSysRoleRes(SysRoleRes sysRoleRes, String saveOrUpdate) throws BusinessException {
		log.info("角色与资源对应关系新增 /修改service层");
		if (saveOrUpdate.equalsIgnoreCase(CRUDCode.Create.value())) {
			String roleId = sysRoleRes.getRoleId();
			String resourceId = sysRoleRes.getResourceId();
			saveSelfAndParentSysRoleRes(roleId, resourceId);
		} else {
			sysRoleRes.update();
		}
		authService.refreshResourceAuth();
	}

	/**
	 * 递归保存当前资源与角色关系以及父级资源与角色关系
	 * 
	 * @throws BusinessException
	 */
	private void saveSelfAndParentSysRoleRes(String roleId, String resourceId) throws BusinessException {
		SysRoleRes sysRoleRes = new SysRoleRes();
		sysRoleRes.setRoleId(roleId);
		sysRoleRes.setResourceId(resourceId);
		sysRoleRes.setIsValid(1);
		sysRoleRes.setCreateTime(new Date());
		sysRoleRes.save();
		SysResource sysResource = SysResource.getBy(resourceId);
		String parent_resource_ids = sysResource.getParent_resource_ids();
		if (StringUtils.isBlank(parent_resource_ids)) {
			return;
		} else {
			String[] parent_resource_array = parent_resource_ids.split(",");
			for (String parent_resource_id : parent_resource_array) {
				// 如果父资源已经绑定了，就不用绑定
				if (!SysRoleRes.isRoleIdAndResourceIdExist(roleId, resourceId)) {
					saveSelfAndParentSysRoleRes(roleId, parent_resource_id);
				}
			}
		}
	}

	/**
	 * 删除角色资源分配
	 */
	public void deleteSysRoleRes(String roleId, String resource_id) {
		log.info("删除角色资源分配service层");
		SysRoleRes sr = SysRoleRes.getBy(roleId, resource_id);
		sr.delete();
		authService.refreshResourceAuth();
	}

	/**
	 * 角色与菜单对应关系查询
	 */
	public List<SysRoleMenu> listSysRoleMenu() {
		log.info("角色与菜单对应关系查询service层");
		List<SysRoleMenu> sysRoleMenuList = SysRoleMenu.getAll();
		return sysRoleMenuList;
	}

	/**
	 * 角色与菜单对应关系新增 /修改
	 */
	public void saveOrUpdateSysRoleMenu(SysRoleMenu sysRoleMenu, String saveOrUpdate) throws BusinessException {
		log.info("角色与菜单对应关系新增 /修改service层");
		if (saveOrUpdate.equalsIgnoreCase(CRUDCode.Create.value())) {
			sysRoleMenu.setCreateTime(new Date());
			sysRoleMenu.save();
		} else {
			sysRoleMenu.update();
		}
		authService.refreshResourceAuth();
	}

	/**
	 * 删除角色菜单分配
	 */
	public void deleteSysRoleMenu(String roleId, String menuId) {
		log.info("删除角色菜单分配service层");
		SysRoleMenu sr = SysRoleMenu.getBy(roleId, menuId);
		sr.delete();
		authService.refreshResourceAuth();
	}

	/**
	 * 订单系统角色查询
	 */
	public List<SysRole> listSysRole() {
		log.info("订单系统角色查询service层");
		List<SysRole> sysRoleList = SysRole.getAll();
		return sysRoleList;
	}

	/**
	 * 运营商列表查询
	 */
	public List<Merchant> listMerchant() {
		log.info("订单系统角色查询service层");
		List<Merchant> merchantList = Merchant.getAll();
		return merchantList;
	}

	/**
	 * 订单报表查询
	 * 
	 * @author Anson
	 * @createDate 2016年4月26日
	 * @desc 根据传入进来的消费开始/结束时间,以及当前的服务编号(服务类型),当前卡号,去查询当前关联的订单信息
	 * 
	 * @param queryOrderResportVO
	 *            服务编号(服务类型)
	 * @return
	 */
	public List<OrderQueryVO> queryOrder(QueryOrderResportVO queryOrderResportVO) {
		log.info("订单报表查询service层");
		return OrderQueryVO.query(queryOrderResportVO);
	}

	/**
	 * 
	 * @param queryOrderResportVO
	 *            查询bean
	 * @param curPageNo
	 *            分页
	 * @param prePageNum
	 *            每页显示条数
	 * @return
	 */
	public Pagination<OrderQueryVO> queryPagition(QueryOrderResportVO queryOrderResportVO, int curPageNo,
			int prePageNum) {
		log.info("订单报表查询service层");
		return queryPagition(queryOrderResportVO, curPageNo, prePageNum, true);
	}

	/**
	 * 
	 * @param queryOrderResportVO
	 *            查询bean
	 * @param curPageNo
	 *            分页
	 * @param prePageNum
	 *            每页显示条数
	 * @param waSentAccounting
	 *            false 时只查询未发送台账的订单
	 * @return
	 */
	public List<ExportOrderItem> export(QueryOrderResportVO queryOrderResportVO ) {
		log.info("订单报表查询service层");
		return OrderQueryVO.export(queryOrderResportVO);
	}

	/**
	 * 导出
	 * @param queryOrderResportVO
	 * @param curPageNo
	 * @param prePageNum
	 * @param waSentAccounting
	 * @return
	 */
	public Pagination<OrderQueryVO> queryPagition(QueryOrderResportVO queryOrderResportVO, int curPageNo,
			int prePageNum, boolean waSentAccounting) {
		log.info("订单报表查询service层");
		return OrderQueryVO.queryPagition(queryOrderResportVO, curPageNo, prePageNum, waSentAccounting);
	}

	/**
	 * 查询订单修改日志
	 * 
	 * @param queryOrderResportVO
	 *            查询bean
	 * @param curPageNo
	 *            分页
	 * @param prePageNum
	 *            每页显示条数
	 * @return
	 * @throws BusinessException
	 */
	public Pagination<OrderChangeLogVo> queryLogPagition(QueryOrderChangeLogResportVO vo, int curPageNo, int prePageNum)
			throws BusinessException {
		log.info("订单报表查询service层");
		return OrderChangeLogVo.queryPagition(vo, curPageNo, prePageNum);
	}

	/**
	 * 获取短信验证码
	 * 
	 * @return
	 */
	public boolean getCheckCode(RetVO retVO) {
		Subject subject = SecurityUtils.getSubject();
		String dzSessionAttrMobileNo = null;
		if (subject.getSession().getAttribute("dzSessionAttrMobileNo") != null) {
			dzSessionAttrMobileNo = (String) subject.getSession().getAttribute("dzSessionAttrMobileNo");
		} else {
			dzSessionAttrMobileNo = queryOperUserBaseInfo();
		}
		if (StringUtils.isEmpty(dzSessionAttrMobileNo)) {
			return false;
		}
		MsRpcClient msRpcClient = SysApplicationContextAware.getBean(MsRpcClient.class);
		String result = msRpcClient.getCheckCode(dzSessionAttrMobileNo);
		if (StringUtils.isEmpty(result)) {
			// 验证码发送失败
			retVO.setErrorMsg("验证码请求发送失败");
			return false;
		}
		JSONObject jsonObject = JSONObject.parseObject(result);
		if (jsonObject.getIntValue("isSuccess") == 1) {
			return true;
		} else {
			retVO.setErrorMsg(jsonObject.getString("errorMsg"));
			return false;
		}
	}

	/**
	 * 查询操作员信息
	 * 
	 * @return
	 */
	private String queryOperUserBaseInfo() {
		String dzSessionAttrMobileNo = null;
		Subject subject = SecurityUtils.getSubject();
		String dzSessionAttrUserId = (String) subject.getSession()
				.getAttribute(RoleAndPermConstants.SESSION_ATTR_USERID);
		MsRpcClient msRpcClient = SysApplicationContextAware.getBean(MsRpcClient.class);
		String result = msRpcClient.queryOperUserBaseInfo(dzSessionAttrUserId, "1");
		if (result != null) {
			JSONObject jsonObject = JSONObject.parseObject(result);
			if (!StringUtils.isEmpty(jsonObject.getString("isSuccess")) && jsonObject.getInteger("isSuccess") == 1) {
				JSONArray array = jsonObject.getJSONArray("result");
				if (array != null && array.size() > 0) {
					dzSessionAttrMobileNo = array.getJSONObject(0).getString("mobileNo");
					subject.getSession().setAttribute("dzSessionAttrMobileNo", dzSessionAttrMobileNo);
				}
			}
		}
		return dzSessionAttrMobileNo;
	}

	/**
	 * 修改订单金额
	 * 
	 * @param itemChangeVo
	 * @throws BusinessException 
	 */
	public void updateOrderAmount(OrderItemChangeVo itemChangeVo, RetVO retVO) throws BusinessException {
		OrderInfo orderInfo = OrderInfo.getById(itemChangeVo.getOrderNo());
		// 订单状态不为未支付
		if (orderInfo.getStatus() != OrderStatus.unPay.value()) {
			retVO.setErrorMsg("订单状态不为未支付");
			return;
		}
		// 已经记录台账信息
		Long num = OrderAccountingStatus.queryNumByOrderNo(itemChangeVo.getOrderNo());
		if (num != null && num != 0) {
			retVO.setErrorMsg("已经记录台账信息");
			return;
		}

		// 校验验证码
		// Subject subject = SecurityUtils.getSubject();
		// String dzSessionAttrMobileNo = null;
		// if (subject.getSession().getAttribute("dzSessionAttrMobileNo") !=
		// null) {
		// dzSessionAttrMobileNo = (String)
		// subject.getSession().getAttribute("dzSessionAttrMobileNo");
		// } else {
		// retVO.setErrorMsg("请重新发送验证码");
		// return;
		// }
		// MsRpcClient client = new MsRpcClient();
		// String result = client.verifyCheckCode(dzSessionAttrMobileNo,
		// itemChangeVo.getCheckCode());
		// JSONObject jsonObject = JSONObject.parseObject(result);
		// if (jsonObject.getIntValue("isSuccess") != 1) {
		// retVO.setErrorMsg("错误信息,请重新发送验证码");
		// return;
		// }
		List<OrderItem> items = OrderItem.getByOrderNo(itemChangeVo.getOrderNo());
		List<OrderItemDividedDetail> dividedDetails;
		saveChangeInfo(itemChangeVo, orderInfo, items);
		List<OrderBaseData> orderBaseDatas = calculateOderItem(itemChangeVo, items);
		items = activityRuleService.caculate(orderBaseDatas);
		// 分润计算
		BigDecimal caculatedTotalPrice = new BigDecimal("0.00");
		for (OrderItem orderItem : items) {
			dividedDetails = OrderItemDividedDetail.getByOrderNoAndServiceNo(orderItem.getItemId());
			orderItem.setOrderNo(itemChangeVo.getOrderNo());
			BigDecimal dividedSum = new BigDecimal("0.00");
			for (int i = 0; i < dividedDetails.size(); i++) {
				OrderItemDividedDetail dividedDetail = dividedDetails.get(i);
				dividedDetail.setTotalPrice(orderItem.getRealTotalPrice());
				BigDecimal currentRatio = dividedDetail.getCurrentRatio();
				if (null == currentRatio) {
					currentRatio = new BigDecimal("1.00");
				}
				BigDecimal splitedPrice = AmountUtil.multiply(orderItem.getRealTotalPrice(), currentRatio);
				// 确保金额相加正确性
				if (i == dividedDetails.size() - 1) {
					splitedPrice = AmountUtil.sub(orderItem.getRealTotalPrice(), dividedSum);
				}
				dividedDetail.setSplitedPrice(splitedPrice);
				dividedSum = AmountUtil.add(dividedSum, splitedPrice);
				// 修改分润列表
				dividedDetail.updateOrderItemDividedDetail();
			}
			caculatedTotalPrice = AmountUtil.add(caculatedTotalPrice, orderItem.getRealTotalPrice());
			// 修改订单项金额
			orderItem.updateOrderItem();
		}

		orderInfo.setCaculatedTotalPrice(caculatedTotalPrice);
		// 更新订单金额
		orderInfo.update();
	}

	/**
	 * 保存修改前的订单相关信息
	 * 
	 * @param itemChangeVo
	 * @param orderInfo
	 * @param items
	 * @throws BusinessException 
	 */
	private void saveChangeInfo(OrderItemChangeVo itemChangeVo, OrderInfo orderInfo, List<OrderItem> items) throws BusinessException {
		// 保存修改之前的信息
		Subject subject = SecurityUtils.getSubject();
		String changeId = UUIDUtil.getCurrentDate14(null) + itemChangeVo.getOrderNo();
		// 保存订单信息日志
		OrderInfoChangeLogInfo orderInfoChangLogInfo = JSONObject.parseObject(JSONObject.toJSON(orderInfo).toString(),
				OrderInfoChangeLogInfo.class);
		orderInfoChangLogInfo.setChangeId(changeId);
		orderInfoChangLogInfo.save();
		// 保存订单项信息日志
		OrderItemChangeLogInfo orderItemChangLog;
		for (OrderItem orderItem : items) {
			orderItemChangLog = JSONObject.parseObject(JSONObject.toJSON(orderItem).toString(),
					OrderItemChangeLogInfo.class);
			orderItemChangLog.setChangeId(changeId);
			orderItemChangLog.save();
		}
		List<OrderItemDividedDetail> dividedDetails = OrderItemDividedDetail.getByOrderNo(itemChangeVo.getOrderNo());
		// 保存订单分润信息日志
		OrderItemDividedDetailChangeLogInfo changLogInfo;
		for (OrderItemDividedDetail orderItemDividedDetail : dividedDetails) {
			changLogInfo = JSONObject.parseObject(JSONObject.toJSON(orderItemDividedDetail).toString(),
					OrderItemDividedDetailChangeLogInfo.class);
			changLogInfo.setChangeId(changeId);
			changLogInfo.save();
		}
		// 保存修改前的订单相关信息
		OrderChangeInfo changeInfo = new OrderChangeInfo();
		changeInfo.setChangeId(changeId);
		changeInfo.setCreateTime(new Date());
		changeInfo.setMsg(itemChangeVo.getMsg());
		changeInfo.setOrderNo(itemChangeVo.getOrderNo());
		changeInfo.setOrderCreateTime(orderInfo.getCreateTime());
		queryOperUserBaseInfo();
		if(subject.getSession().getAttribute("dzSessionAttrMobileNo")==null){
			throw new BusinessException("获取操作员信息失败");
		}
		changeInfo.setUserMobileNo(subject.getSession().getAttribute("dzSessionAttrMobileNo").toString());
		changeInfo.setUserId(subject.getSession().getAttribute(RoleAndPermConstants.SESSION_ATTR_USERID).toString());
		changeInfo.save();
	}

	/**
	 * 计算订单项价格
	 * 
	 * @param itemChangeVo
	 * @param retVO
	 */
	public List<OrderQueryVO> calculateOrderPrice(OrderItemChangeVo itemChangeVo) {
		List<OrderItem> items = OrderItem.getByOrderNo(itemChangeVo.getOrderNo());
		List<OrderBaseData> orderBaseDatas = calculateOderItem(itemChangeVo, items);
		List<OrderQueryVO> orderQueryVOs = new ArrayList<OrderQueryVO>();
		items = activityRuleService.caculate(orderBaseDatas);
		orderBaseDatas.clear();
		OrderInfo orderInfo = OrderInfo.getById(itemChangeVo.getOrderNo());
		OrderQueryVO orderQueryVO;
		for (OrderItem orderItem : items) {
			orderItem.setOrderNo(orderInfo.getOrderNo());
			orderQueryVO = OrderQueryVO.queryOrderItembyOrderItemId(orderItem);
			orderQueryVO.setBuyNum(orderItem.getBuyNum());
			orderQueryVO.setUnitPrice(orderItem.getUnitPrice());
			orderQueryVO.setItemId(orderItem.getItemId());
			orderQueryVO.setTotalPrice(orderItem.getTotalPrice());
			orderQueryVO.setRealTotalPrice(orderItem.getRealTotalPrice());
			orderQueryVOs.add(orderQueryVO);
		}
		// itemChangeVo.setOrderBaseDatas(orderBaseDatas);
		return orderQueryVOs;
	}

	/**
	 * 计算打折后的订单详情信息
	 * 
	 * @param itemChangeVo
	 * @return
	 */
	private List<OrderBaseData> calculateOderItem(OrderItemChangeVo itemChangeVo, List<OrderItem> items) {
		List<OrderBaseData> orderBaseDatas = new ArrayList<OrderBaseData>();
		OrderInfo orderInfo = OrderInfo.getById(itemChangeVo.getOrderNo());
		for (OrderItem orderItem : items) {
			for (OrderBaseData orderBaseData : itemChangeVo.getOrderBaseDatas()) {
				if (orderItem.getItemId().equals(orderBaseData.getItemId())) {
					OrderBaseData baseData = new OrderBaseData(orderInfo, orderItem);
					if (orderBaseData.getBuyNum() == null || orderBaseData.getBuyNum().doubleValue() < 0) {
						orderBaseData.setBuyNum(new BigDecimal("0.00"));
					}
					baseData.setBuyNum(orderBaseData.getBuyNum());
					baseData.setItemId(orderItem.getItemId());
					// 优先使用单价计算
					if (orderBaseData.getUnitPrice() == null) {
						if (null == orderBaseData.getTotalPrice() || orderBaseData.getTotalPrice().doubleValue() < 0) {
							orderBaseData.setTotalPrice(new BigDecimal("0.00"));
						}
						baseData.setTotalPrice(orderBaseData.getTotalPrice());
					} else {
						if (orderBaseData.getUnitPrice().doubleValue() < 0) {
							orderBaseData.setUnitPrice(new BigDecimal("0.00"));
						}
						baseData.setUnitPrice(orderBaseData.getUnitPrice());
						baseData.setTotalPrice(null);
					}
					orderBaseDatas.add(baseData);
				}
			}
		}
		return orderBaseDatas;
	}


	/**
	 * 查询订单修改日志
	 *
	 * @param vo
	 *            查询bean
	 * @param curPageNo
	 *            分页
	 * @param prePageNum
	 *            每页显示条数
	 * @return
	 * @throws BusinessException
	 */
	public Pagination<OrderAlreadyPaid> queryOrderAlreadyPaidPagition(OrderAlreadyPaidVo vo, int curPageNo, int prePageNum)
			throws BusinessException {
		log.info("订单报表查询service层");
		return OrderAlreadyPaidVo.queryPagition(vo, curPageNo, prePageNum);
	}
	/**
	 * 查询订单修改日志
	 *
	 * @param vo
	 *            查询bean
	 * @param curPageNo
	 *            分页
	 * @param prePageNum
	 *            每页显示条数
	 * @return
	 * @throws BusinessException
	 */
	public Pagination<OrderAlreadyPaid> queryOrderPayPagition(OrderPayVo vo, int curPageNo, int prePageNum)
			throws BusinessException {
		log.info("订单报表查询service层");
		return OrderPayVo.queryPagition(vo, curPageNo, prePageNum);
	}
	/**
	 * 查询订单修改日志
	 *
	 * @param vo
	 *            查询bean
	 * @param curPageNo
	 *            分页
	 * @param prePageNum
	 *            每页显示条数
	 * @return
	 * @throws BusinessException
	 */
	public Pagination<OrderPayInfo> queryOrderPayLogPagition(OrderPayLogVo vo, int curPageNo, int prePageNum)
			throws BusinessException {
		log.info("订单报表查询service层");
		return OrderPayLogVo.queryPagition(vo, curPageNo, prePageNum);
	}

	public void pay(OrderAlreadyPaid vo ,String checkCode)
			throws BusinessException {
		log.info("支付宝转账service层");
		Subject subject = SecurityUtils.getSubject();
		String dzSessionAttrUserId = (String) subject.getSession()
				.getAttribute(RoleAndPermConstants.SESSION_ATTR_USERID);

        String dzSessionAttrMobileNo = null;
        if (subject.getSession().getAttribute("dzSessionAttrMobileNo") != null) {
            dzSessionAttrMobileNo = (String) subject.getSession().getAttribute("dzSessionAttrMobileNo");
        } else {
            dzSessionAttrMobileNo = queryOperUserBaseInfo();
        }
        if (StringUtils.isEmpty(dzSessionAttrMobileNo)) {
            throw new RuntimeException("验证码错误" );
        }
        MsRpcClient msRpcClient = SysApplicationContextAware.getBean(MsRpcClient.class);
        String result = msRpcClient.verifyCheckCode(dzSessionAttrMobileNo, checkCode);
        JSONObject obj = JSONObject.parseObject(result);
        if (!"1".equals(obj.getString("isSuccess"))) {
            throw new RuntimeException("验证码错误:"+ obj.getString("errorMsg"));
        }

		pay(vo, dzSessionAttrUserId,false);
	}

	public void pay(OrderAlreadyPaid vo, String dzSessionAttrUserId,boolean auto) {
		MerchantVO mvo = new MerchantVO();
		OrderPayInfo order = new OrderPayInfo();
		order.setCreateTime(new Date());
		order.setStatus(OrderStatus.payedDone.value());
		order.setOrderNo(new StringBuilder(UUIDUtil.getCurrentDate14(null)).append(UUIDUtil.randomNum(4)).toString());
		order.setCaculatedTotalPrice(vo.getPayPrice());
		order.setMerchantCode(vo.getMerchantCode());
		if(!auto){
			order.setUserId(dzSessionAttrUserId);
		}
		mvo = mvo.queryMerchantByCode(vo.getMerchantCode());
		try {
			AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appid, privatekey, "json", "GBK", publickey, "RSA2");
			AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
			request.setBizContent("{" +
					"\"out_biz_no\":\"" + order.getOrderNo() + "\"," +
					"\"payee_type\":\"ALIPAY_LOGONID\"," +
					"\"payee_account\":\"" + mvo.getAlipay() + "\"," +
					"\"amount\":\"" + order.getCaculatedTotalPrice().doubleValue() + "\"," +
					"\"payer_show_name\":\"四川豪特新能有限公司\"" +
					"}");
			AlipayFundTransToaccountTransferResponse response = alipayClient.execute(request);
			if (response.isSuccess()) {
				order.save();
			} else {
				throw new RuntimeException("调用支付宝发送错误" + response.getSubMsg());
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("调用支付宝发送错误" + e.getMessage());
		}
	}
}
